package com.vector.ding.web.service.baseinfo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.vector.ding.commons.ActionResult;
import com.vector.ding.commons.BizConstant;
import com.vector.ding.commons.Constant;
import com.vector.ding.commons.util.BeanUtil;
import com.vector.ding.commons.util.StringUtil;
import com.vector.ding.commons.util.collection.CollectionUtil;
import com.vector.ding.commons.util.file.ExcelUtil;
import com.vector.ding.commons.util.web.RequestUtil;
import com.vector.ding.dao.mybatis.mapper.ZmjgBaseInfoMapper;
import com.vector.ding.dao.mybatis.model.ZmjgBaseInfo;
import com.vector.ding.dao.mybatis.model.ZmjgBaseInfoExample;
import com.vector.ding.exception.BaseException;

@Service
public class YzgsBaseInfoMgrService {
	
	@Autowired
	private ZmjgBaseInfoMapper baseMapper;
	
	private static Logger logger = LoggerFactory.getLogger(GqtzgsBaseInfoMgrService.class);

	public ZmjgBaseInfo getBaseInfo(String number) {
		return baseMapper.selectByPrimaryKey(number);
	}
    
	public ZmjgBaseInfo getBaseInfoByName(String companyName) {
		ZmjgBaseInfoExample example = new ZmjgBaseInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		List<ZmjgBaseInfo> list = baseMapper.selectByExample(example);
		return CollectionUtil.isEmpty(list) ? null : list.get(0);
	}
	
	public List<ZmjgBaseInfo> getBaseInfo(int pageIndex, int pageSize,
			HttpServletRequest request) {
		if (pageSize != Integer.MAX_VALUE)
			PageHelper.startPage(pageIndex, pageSize, true);
		ZmjgBaseInfoExample example = getBaseInfoExample(request);
		return baseMapper.selectByExample(example);
	}
	
	public List<ZmjgBaseInfo> getRecords(int pageIndex, int pageSize,
			String nameLike) {
		if (pageSize != Integer.MAX_VALUE)
			PageHelper.startPage(pageIndex, pageSize, true);
		ZmjgBaseInfoExample example = new ZmjgBaseInfoExample();
		String companyName = StringUtil.getString(nameLike).trim();
		example.or().andCompanyNameLike(StringUtil.wrapString(companyName, "%", "%"));
		return baseMapper.selectByExample(example);
	}
	
	public List<Map<String, Object>> getAllRecords() {
		List<ZmjgBaseInfo> list = baseMapper.selectByExample(null);
		List<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
		if (CollectionUtil.isEmpty(list))
			return records;
		
		for (ZmjgBaseInfo baseInfo: list) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("value", baseInfo.getNumber());
			map.put("text", baseInfo.getCompanyName());
			records.add(map);
		}
		return records;
	}

	private ZmjgBaseInfoExample getBaseInfoExample(HttpServletRequest request) {
		ZmjgBaseInfoExample example = new ZmjgBaseInfoExample();
		String companyName = StringUtil.getString(request.getParameter("company_name")).trim();
		example.or().andCompanyNameLike(StringUtil.wrapString(companyName, "%", "%"));
		return example;
	}

	public ZmjgBaseInfo getBaseInfoBean(HttpServletRequest request) {
		Map<String, Object> paramMap = RequestUtil.getParamMap(request);
		Set<String> excludeProSet = CollectionUtil.asSet("registerFund");
		ZmjgBaseInfo baseInfo = new ZmjgBaseInfo();
		BeanUtil.fillBeanProperty(paramMap, baseInfo, excludeProSet);
		baseInfo.setRegisterFund(ExcelUtil.getDecimalValue(
				StringUtil.getString(paramMap.get("registerFund"))));
		if (StringUtil.isEmpty(baseInfo.getNumber()))
			baseInfo.setNumber(StringUtil.getUuid());
		
		return baseInfo;
	}

	public JSONObject insertBaseInfo(ZmjgBaseInfo baseInfo) {
		if (existRecord(baseInfo.getNumber()))
			return ActionResult.fail(String.format("新增失败：存在编号为[%s]的记录!", baseInfo.getNumber()));
		
		int cnt = 0;
		try {
			cnt = baseMapper.insertSelective(baseInfo);
		} catch (Exception e) {
			if (logger.isDebugEnabled())
				e.printStackTrace();
		}
		if (cnt == 0) {
			logger.error("插入小贷投资公司基本信息记录失败：number为{}...", baseInfo.getNumber());
		}
			
		return cnt != 0 ? ActionResult.success() : 
			ActionResult.fail(String.format("新增记录失败"));
	}
	
	public JSONObject updateBaseInfo(ZmjgBaseInfo baseInfo) {
		if (!existRecord(baseInfo.getNumber()))
			return ActionResult.fail(String.format("更新失败：不存在编号为[%s]的记录!", baseInfo.getNumber()));
		int cnt = baseMapper.updateByPrimaryKeySelective(baseInfo);
		if (cnt == 0) {
			logger.error("更新小贷投资公司基本信息记录失败：未找到number为{}的记录...", baseInfo.getNumber());
		}
			
		return cnt != 0 ? ActionResult.success() : 
			ActionResult.fail(String.format("更新基本信息记录失败，编号为[%s]", baseInfo.getNumber()));
	}
	
	public boolean existRecord(String number) {
		ZmjgBaseInfoExample example = new ZmjgBaseInfoExample();
		example.or().andNumberEqualTo(number);
		return baseMapper.countByExample(example) != 0;
	}

	public JSONObject delete(String[] ids) {
		int count = Constant.DaoOperation.UPDATE_FAILURE ;
		if (ids == null || ids.length == 0)
			count = 0;
		
		try {
			for (String id: ids) {
				// 删除业务1表中同名公司的记录数据
				ZmjgBaseInfo baseInfo = getBaseInfo(id);
				if (baseInfo == null)
					continue;
				
				count += baseMapper.deleteByPrimaryKey(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (count == Constant.DaoOperation.UPDATE_FAILURE)
			return ActionResult.fail("删除失败！");
		return ActionResult.success();
	}

	public void importFormFile(File importFile) {
		HSSFWorkbook workBook = null;
		int rowIndex = 0;
		try {
			workBook = new HSSFWorkbook(FileUtils.openInputStream(importFile));
			HSSFSheet sheet = workBook.getSheetAt(BizConstant.Yzgs.Base.SHEET_NUM);
			
			int rowNum = sheet.getLastRowNum();
			for (rowIndex = BizConstant.Yzgs.Base.START_ROW_NUM; rowIndex <= rowNum; ++rowIndex) {
				HSSFRow row = sheet.getRow(rowIndex);
				if (isEnd(row))
					break;

				boolean needImport = checkRowData(row);
				if (!needImport)
					continue;
				//RzdbgsBizInfo1 bean = getBaseInfoBean(row);
				ZmjgBaseInfo bean = getBaseInfoBean(row);
				baseMapper.insertSelective(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
//			throw new BaseException(e);
			throw new BaseException(String.format("第%s行数据格式有误，请检查数据！", rowIndex));
		} finally {
			if (workBook != null) {
				try {
					workBook.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new BaseException(e);
				}
			}
		}
	}

	private ZmjgBaseInfo getBaseInfoBean(HSSFRow row) {
		ZmjgBaseInfo bean = new ZmjgBaseInfo();
		
		bean.setNumber(StringUtil.getUuid());
		bean.setCompanyName(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.COMPANY_NAME_CELL));
		//bean.setCompanyType(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.COMPANY_TYPE_CELL));
		bean.setDelegatePeople(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.DELEGATE_PEOPLE_CELL));
		bean.setEstablishDate(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.ESTABLIST_DATE_CELL));
		bean.setManageContent(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.MANAGE_CONTENT_CELL));
//		bean.setNumber(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.NUMBER_CELL));
		bean.setRegisterAddress(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.REG_ADDRESS_CELL));
		bean.setRegisterCurrency(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.REG_CURRENCY_CELL));
		bean.setRegisterFund(ExcelUtil.getDecimalValue(row.getCell(BizConstant.Yzgs.Base.REG_FUND_CELL)));
		bean.setRegisterLocation(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.REG_LOCATION_CELL));
		bean.setXz(ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.XZ_CELL));
		
		return bean;
	}
	
	private boolean isEnd(HSSFRow row) {
		String stringValue = row.getCell(BizConstant.Xedkgs.Base.NUMBER_CELL).toString();
		if (StringUtil.isEmpty(stringValue))
			return true;
		
		return false;
	}
	
	public boolean existComapny(String companyName) {
		ZmjgBaseInfoExample example = new ZmjgBaseInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		return baseMapper.countByExample(example) != 0;
	}

	private boolean checkRowData(HSSFRow row) {
//		if (row.getCell(BizConstant.Gqtzgs.Base.NUMBER_CELL) == null)
//			return false;
//		String number = StringUtil.getString((int)row.getCell(BizConstant.Gqtzgs.Base.NUMBER_CELL).getNumericCellValue());
//		if (StringUtil.isEmpty(number))
//			return false;
		
		if (row.getCell(BizConstant.Yzgs.Base.COMPANY_NAME_CELL) == null)
			return false;
		String companyName = ExcelUtil.getRowCellStringValue(row, BizConstant.Yzgs.Base.COMPANY_NAME_CELL);
		if (StringUtil.isEmpty(companyName))
			return false;
		return !existComapny(companyName);
	}

}
